/**
 * CommonUtil.java
 * 版权所有(C) 2013
 * 创建者:cuiran 2013-11-16 上午11:24:02
 */
package com.ghyf.mplay.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.view.Display;

import com.example.watchdog.Watchdog;
import com.ghyf.mplay.util.ShellUtils.CommandResult;
import com.ghyf.mplay.value.ConstantValue;
import com.reset.cpu.SHOT;

/**
 * 系统操作的工具类 
 * @author cuiran
 * @version 1.0.0
 */
public class CommonUtil {

	private static final String TAG="CommonUtil";
	/**
	 * 用来判断服务是否运行.
	 * 
	 * @param context
	 * @param className
	 *            判断的服务名字
	 * @return true 在运行 false 不在运行
	 */
	public static boolean isServiceRunning(Context context, String className) {
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> serviceinfos = am.getRunningServices(100);
		for (RunningServiceInfo info : serviceinfos) {
			// System.out.println(info.service.getClassName()+"--->"+className);
			if (className.equals(info.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	
	/**
	 * 
	 *<b>function:</b>通过name找到资源文件id
	 *@author cuiran
	 *@createDate 2013-7-18 下午5:19:14
	 *@param packageName
	 *@param className
	 *@param name
	 *@return
	 */
	@SuppressWarnings("rawtypes")
	public static  int getResourseIdByName(String packageName, String className, String name) { 
        int id = 0; 
        try { 
            Class desireClass = Class.forName(packageName + ".R$" + className); 
            if (desireClass != null) 
            id = desireClass.getField(name).getInt(desireClass); 

        } catch (ClassNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IllegalArgumentException e) { 
            e.printStackTrace(); 
        } catch (SecurityException e) { 
            e.printStackTrace(); 
        } catch (IllegalAccessException e) { 
            e.printStackTrace(); 
        } catch (NoSuchFieldException e) { 
            e.printStackTrace(); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 

        return id; 
    }

	/**
	 * 获取打车系统当前的版本号
	 * @param context
	 * @return
	 */
	public static String getVersion(Context context) {
//		Properties pro = new Properties();
//		try {
//			pro.load(context.getResources().openRawResource(
//					com.wpn.R.raw.taxi));
//		} catch (NotFoundException e) {
//			Log.e("GETFILE", "file not found", e);
//		} catch (IOException e) {
//			Log.e("GETFILE", "file io error", e);
//		}
//		String version = (String) pro.get("version");
		String version = "";
		try {
			String packageName = context.getPackageName();
			version = context.getPackageManager().getPackageInfo(packageName, 0).versionName;
		} catch (NameNotFoundException e) {
			
			e.printStackTrace();
		}
		
		return version;
	}
	
	/**
	 * 获取当前手机的分辨率
	 * @param context
	 * @return
	 */
	public static String getResolution(Activity context){
		Display display= context.getWindowManager().getDefaultDisplay();
		Point size=new Point();
		display.getSize(size);
		int width = size.x;
		int height = size.y;
		return width + "*" + height;
	}
	//guanghuali1010&nbsp;
	 public static String htmlToText(String html){
		 if(null!=html&&!"".equals(html)){
			 
			 html=html.replace("&quot;", "\"");
			 html=html.replace("&nbsp;", " ");
			 html=html.replace("&lt;", "<");
			 html=html.replace("&gt;", ">");
			 html=html.replace("&gt;", ">");
			 html=html.replace("<br />", "");
		 }
		
		 return html;
	 }
	 
	// 决定用AudioManager来调节音量
	public static void setPalyVolume(Activity act) {
			AudioManager am = null;
			am = (AudioManager) act.getSystemService(Context.AUDIO_SERVICE);
			am.setStreamVolume(AudioManager.STREAM_MUSIC,
					am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
					AudioManager.FLAG_PLAY_SOUND);
	}

	 
	 public static String removeToText(String html){
		 if(null!=html&&!"".equals(html)){
			 
			 html=html.replace("<", "");
			 html=html.replace(">", "");
			
		 }
		
		 return html;
	 }
	 /**
	  * 重启
	  * 2013-11-29 下午3:33:22
	  * @param context
	  * @return
	  *
	  */
	 public static boolean reboot(Context context){
		 try {

			 	Runtime.getRuntime().exec(new String[] { "su", "-c", "reboot now" });

			 } catch (IOException e) {
				new AlertDialog.Builder(context).setTitle("Error").setMessage(e.getMessage()).setPositiveButton("OK", null).show();
			 }
		 return true;
	 }
	 @SuppressLint("SdCardPath")
	public static boolean chmodeth(){
		 
			CommandResult cr = ShellUtils.execCommand("chmod 777 /mnt/sdcard/eth0.sh",ShellUtils.checkRootPermission()) ;
			LogUtil.i(TAG, "chmodeth：successMsg="+cr.successMsg+"-result="+cr.result+"-errorMsg="+cr.errorMsg);
	
			return true;
	 }
	 
	 public static boolean settime(Context context){
		 	try {
		 		 LogUtil.i(TAG, "settime=");
			 	execShellStr("date -s 20131213.174500");
			 } catch (Exception e) {
				new AlertDialog.Builder(context).setTitle("Error").setMessage(e.getMessage()).setPositiveButton("OK", null).show();
			 }
		 return true;
	 }
	 
	  public static void execShellStr(String cmd)
	    {
		  LogUtil.i(TAG, "retString="+cmd);
	    	//"su", "su",
	        String[] cmdStrings = new String[] {"sh","-c","su",cmd};
	        String retString = "";
	        try
	        {
	            Process process = Runtime.getRuntime().exec(cmdStrings);
	            BufferedReader stdout =
	            new BufferedReader(new InputStreamReader(
	                process.getInputStream()), 7777);
	            BufferedReader stderr =
	            new BufferedReader(new InputStreamReader(
	                process.getErrorStream()), 7777);
	            String line = null;
	            while ((null != (line = stdout.readLine()))
	            || (null != (line = stderr.readLine())))
	            {
	            if (null!=line)
	            {
	                retString += line + "\n";
	            }
	            }
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();
	        }

	        LogUtil.i(TAG, "retString="+retString);
	    }
	 
	 @TargetApi(Build.VERSION_CODES.FROYO)
	public static boolean reboot1(Context context){
		 // 重启  
         /*String str = "重启"; 
         try { 
             str = runCmd("reboot", "/system/bin"); 
         } catch (IOException e) { 
             e.printStackTrace(); 
         }*/  
         /*Intent reboot = new Intent(Intent.ACTION_REBOOT);   
         reboot.putExtra("nowait", 1);   
         reboot.putExtra("interval", 1);   
         reboot.putExtra("window", 0);   
         sendBroadcast(reboot); */   
         PowerManager pManager=(PowerManager)context.getSystemService(Context.POWER_SERVICE);  
         pManager.reboot("重启");  
         System.out.println("execute cmd--> reboot\n" + "重启");  
         return true;
	 }
	 
	 public static boolean checkSDcard() {
			String sdStutusString = Environment.getExternalStorageState();
			if (sdStutusString.equals(Environment.MEDIA_MOUNTED)) {
				return true;
			} else {
				return false;
			}
		}
	 public static void reboot1(){
		 Watchdog dog=Watchdog.getInstance();
		 int n=dog.reset();
		 LogUtil.i(TAG, "reboot n="+n);   
	 }
	 /**
	  * 重启系统<br>
	  * 2014-8-25 上午11:46:46
	  *
	  */
	 public static void reboot(){
  
		 Watchdog dog=Watchdog.getInstance();
		 int n=dog.reset();
		 LogUtil.i(TAG, "reboot n="+n);   
	 }
	 /**
	  * 重启软件<br>
	  * 2014-8-25 上午11:46:34
	  *
	  */
	 public static void reSoftWare(Context context){
		 try{
			  Intent myIntent = new Intent(ConstantValue.RESOFTWARE_RECEIVER);  
			  myIntent.putExtra("path", ConstantValue.COMMAND_INSTALL_APP);
			  myIntent.setAction(ConstantValue.RESOFTWARE_RECEIVER);  
			  context.sendBroadcast(myIntent);  
		 }catch(Exception e){
			 LogUtil.e(TAG, "reSoftWare error",e);
		 }
		
	 }
	 public static void shot(SHOT jni){
		
		  
//	    	int n= jni.write(m,1,ConstantValue.ROOT_SDCARD_DIR+"a.bmp");
	    	jni.setname();
//	    	LogUtil.i(TAG, "shot n="+n);   
	 }
	 
	 public static Bitmap fitSizeImg(String path) {
         if(path == null || path.length()<1 ) return null;
         File file = new File(path);
         Bitmap resizeBmp = null;
         BitmapFactory.Options opts = new   BitmapFactory.Options();
         // 数字越大读出的图片占用的heap越小 不然总是溢出
         if (file.length() < 20480) {       // 0-20k
          opts.inSampleSize = 1;
         } else if (file.length() < 51200) { // 20-50k
          opts.inSampleSize = 2;
         } else if (file.length() < 307200) { // 50-300k
          opts.inSampleSize = 4;
         } else if (file.length() < 819200) { // 300-800k
          opts.inSampleSize = 6;
         } else if (file.length() < 1048576) { // 800-1024k
          opts.inSampleSize = 8;
         } else {
          opts.inSampleSize = 10;
         }
         resizeBmp = BitmapFactory.decodeFile(file.getPath(), opts);
         return resizeBmp;
       }

	 /**
	  * 检查网络
	  * 2013-12-18 上午11:16:03
	  * @param context
	  * @return
	  *
	  */
	 public static boolean isNetworkConnected(Context context) {  
		  
		    	 ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);   
		         if (connectivity == null) {   
		             LogUtil.i("NetWorkState", "Unavailabel");   
		             return false;   
		         } else {   
		             NetworkInfo[] info = connectivity.getAllNetworkInfo();   
		             if (info != null) {   
		                 for (int i = 0; i < info.length; i++) {   
		                     if (info[i].getState() == NetworkInfo.State.CONNECTED) {   
		                    	 LogUtil.i("NetWorkState", "Availabel");   
		                         return true;   
		                     }   
		                 }   
		             }   
		         }   
		         return false;   
		     
		}
}
